import {Component, Input, OnInit} from '@angular/core';
import {
  ActionSheetController, AlertController,
  Events,
  LoadingController,
  ModalController,
  Platform,
  PopoverController,
  ToastController
} from '@ionic/angular';
import {FilePath} from '@ionic-native/file-path/ngx';
import {Camera, CameraOptions} from '@ionic-native/camera/ngx';
import {File} from '@ionic-native/file/ngx';
import {FileTransfer, FileTransferObject, FileUploadOptions} from '@ionic-native/file-transfer/ngx';
import {Storage} from '@ionic/storage';
import {UrlAndOPT} from '../../common/url-and-opt.enum';
import {AppConfig} from '../../common/app-config.enum';
import {BidItemComponent} from '../bid-item/bid-item.component';
import {ConfigService} from '../../services/config.service';
import {HttpService} from '../../services/http.service';
import {WebView} from '@ionic-native/ionic-webview/ngx';

@Component({
  selector: 'app-loan-upload-items',
  templateUrl: './loan-upload-items.component.html',
  styleUrls: ['./loan-upload-items.component.scss']
})
export class LoanUploadItemsComponent implements OnInit {

  @Input() title = '附件列表';
  @Input() userItems: any[] = [];
  @Input() bidId: string;
  @Input() bidAuditSubjectId: string;
  public userInfo: any;
  public uploadFilePath = null; // 最终文件路径(上传用)
  public fileName: string; // 文件名
  public fileSuffix = '.jpg'; // 默认文件后缀
  private cameraOptions: CameraOptions = {
    destinationType: this.camera.DestinationType.FILE_URI,
    quality: 50,
    saveToPhotoAlbum: false, // 拍照后是否保存到相册
    correctOrientation: true, // 是否纠正拍摄的照片方向
    targetWidth: 1024,
    targetHeight: 1024
  };

  constructor(
    public configService: ConfigService,
    private modalCtrl: ModalController,
    private popoverCtrl: PopoverController,
    private toastCtrl: ToastController,
    private actionSheetCtrl: ActionSheetController,
    private alertCtrl: AlertController,
    private loadingCtrl: LoadingController,
    private storage: Storage,
    private events: Events,
    private platform: Platform,
    private webview: WebView,
    private camera: Camera,
    private file: File,
    private filePath: FilePath,
    private fileTransfer: FileTransfer,
    private service$: HttpService
  ) {
  }

  ngOnInit() {
    this.getUserInfo();
  }

  // 获取用户信息
  private async getUserInfo() {
    this.userInfo = await this.storage.get(AppConfig.USER_INFO);
  }

  // 附件预览
  async presentPopover(url: string) {
    if (url) {
      // const popover = await this.popoverCtrl.create({
      //   component: BidItemComponent,
      //   componentProps: {
      //     image_url: url
      //   }
      // });
      // await popover.present();
      const modal = await this.modalCtrl.create({
        component: BidItemComponent,
        componentProps: {
          title: this.title,
          image_url: url
        }
      });
      await modal.present();
    } else {
      await this.showToast('没有相关附件');
    }
  }

  // 提交或删除附件
  changeItem(bidItemId: string, action: number) {
    const isSubmit: boolean = (action > 0); // 判断是否为提交
    this.service$.doRequest(isSubmit ? UrlAndOPT.loan_upload_submit : UrlAndOPT.loan_upload_delete, {bidItemId: bidItemId})
      .subscribe(obj => {
        if (obj) {
          if (isSubmit) {
            this.userItems = this.userItems.map(item => {
              if (item['id'] === bidItemId) {
                return {...item, status: 'WAIT_AUDIT'};
              }
              return item;
            });
          } else {
            this.userItems = this.userItems.filter(item => item['id'] !== bidItemId);
          }
          // 发送附件变更通知
          this.events.publish(AppConfig.TOPIC_USER_ITEMS);
          this.showToast(isSubmit ? '提交成功' : '删除成功');
        }
      });
  }

  // 打开图片来源actionsheet
  async presentActionSheet() {
    const actionSheet = await this.actionSheetCtrl.create({
      buttons: [
        {
          text: '相册选择',
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
          }
        }, {
          text: '拍摄照片',
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.CAMERA);
          }
        }, {
          text: '取消',
          role: 'cancel'
        }
      ]
    });
    await actionSheet.present();
  }

  private async takePicture(sourceType: number) {
    try {
      this.cameraOptions.sourceType = sourceType;
      const imagePath = await this.camera.getPicture(this.cameraOptions);
      let path = '';
      if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) { // 来源android相册
        path = await this.filePath.resolveNativePath(imagePath);
      } else { // 其它来源
        path = imagePath;
      }
      this.fileName = path.substr(path.lastIndexOf('/') + 1); // 获取文件名
      this.fileSuffix = this.fileName.substring(this.fileName.lastIndexOf('.')); // 获取后缀名
      this.uploadFilePath = path;
      // 打开确认上传提示
      await this.confirmUpload();
    } catch (e) {
      // 未选择或选择出错关闭页面
      console.log(e);
    }
  }

  // 确认上传提示
  async confirmUpload() {
    const alert = await this.alertCtrl.create({
      header: '提示',
      message: '您确定要上传此附件码？',
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: () => {
            this.uploadFilePath = null;
          }
        }, {
          text: '确定',
          handler: () => {
            this.uploadImage();
          }
        }
      ]
    });
    return alert.present();
  }

  // 执行上传
  async uploadImage() {
    const loading = await this.loadingCtrl.create({
      message: '上传中'
    });
    await loading.present();
    try {
      // 上传的参数 File imgFile, String fileName, String userId
      const fileUploadOptions = {
        fileKey: 'imgFile',
        fileName: this.fileName,
        chunkedMode: false,
        mimeType: 'multipart/form-data',
        params: {
          'userId': this.userInfo['userId'],
          'fileName': this.fileName,
          'bidId': this.bidId,
          'bidAuditSubjectId': this.bidAuditSubjectId
        }
      } as FileUploadOptions;
      // 创建传输对象
      const fileTransferObject: FileTransferObject = this.fileTransfer.create();
      console.log('上传附件本地路径:', this.uploadFilePath);
      // 开始上传
      const uploadPromise$ = fileTransferObject.upload(this.uploadFilePath, UrlAndOPT.HOST + UrlAndOPT.USER_ITEMS, fileUploadOptions);
      // 加入超时机制
      const fileUploadResult = await this.setTimeOverPromise(uploadPromise$);
      const response = JSON.parse(fileUploadResult.response);
      console.log('上传附件结果:', response);
      await loading.dismiss();
      if (response['code'] > 0) {
        this.userItems.push({
          ...response['obj'],
          url: UrlAndOPT.HOST + response['obj']['url']
        });
        this.uploadFilePath = null;
        // 发送附件变更通知
        this.events.publish(AppConfig.TOPIC_USER_ITEMS);
        await this.showToast('上传成功');
      } else {
        await this.showToast('上传失败');
      }
    } catch (e) {
      await loading.dismiss();
      await this.showToast('文件发送失败，请重新上传');
    }
  }

  // 设置上传超时机制
  async setTimeOverPromise(promise$: Promise<any>): Promise<any> {
    const timeout$ = new Promise<number>((resolve, reject) => setTimeout(() => reject('timeout'), 10000));
    return await Promise.race([timeout$, promise$]);
  }

  // 去除路径的file://前缀，转为页面可读取的路径
  private convertPath(filePath: string): string {
    if (filePath) {
      return this.webview.convertFileSrc(filePath) + '?timestamp=' + new Date().getTime();
    }
    return '';
  }

  public closeModal() {
    this.modalCtrl.dismiss().catch(() => {
    });
  }

  async showToast(txt: string) {
    const toast = await this.toastCtrl.create({
      message: txt,
      position: AppConfig.TOAST_POSITION,
      duration: AppConfig.TOAST_DURATION * 1
    });
    return toast.present();
  }

}
